---
title: "Replication_Political_Attitudes_Debus_Himmelrath_Stecker"
subtitle: ""
date: "`r format(Sys.time(), '%d %B, %Y')`"
author: | 
  | Marc Debus
  | Noam Himmelrath
  | Christian Stecker 
output: 
  html_document:
    css: css/stylesheet.css
always_allow_html: yes
---

# Setup

```{r, include=FALSE}
# libraries
pacman::p_load(
  tidyverse,
  sjlabelled,
  DT,
  stringi,
  ggthemes,
  clarify,
  nnet,
  marginaleffects,
  sjPlot,
  ggtext,
  stargazer
  )

# load data
dezimsurvey <- readRDS("dezimsurvey.rds")


# some definitions
party_names <- c("afd" = "AfD", 
                 "gru" = "Grüne", 
                 "cdu" = "CDU", 
                 "csu" = "CSU",
                 "fdp" = "FDP", 
                 "pds" = "Linke", 
                 "spd" = "SPD",
                 "oth" = "Andere")

party_colors <- c("afd" = "blue", 
                  "gru" = "#32CD32", 
                  "cdu" = "black", 
                  "csu" = "grey20", 
                  "fdp" = "#FFD600", 
                  "pds" = "deeppink", 
                  "spd" = "#E3000F"
                  )

dezimsurvey$MigHin_short <- relevel(dezimsurvey$MigHin_short, ref = "none")
```


# Results in Main Text

## Migration background and country of birth

This code replicates figure 1.

```{r, echo=FALSE, message=FALSE, warning = FALSE, fig.align='center'}
dezimsurvey %>% 
  drop_na(MigHin_short, birthcntry_not_deu) %>% 
  count(MigHin_short, birthcntry_not_deu) %>% 
  ggplot(aes(x = MigHin_short, y = n, fill = as.factor(birthcntry_not_deu))) +
  geom_bar(position = "stack", stat = "identity") +
  guides(fill = guide_legend(title = "country of birth")) +
  coord_flip() +
  labs(x = "migration background", 
       y = "number of respondents") +
  theme_bw() +
  scale_fill_manual(
    values = c("#729ece",	"#ff9e4a"),
    labels = c("Germany", "outside Germany")) +
  labs(title = "") +
  theme(
    legend.position = "bottom"
  )
ggsave("graphs/fig1_descr_migback_birth.jpeg", dpi = 300, device = "jpeg")
```

## Positions on issue-dimensions

This code replicates figure 2.

```{r, echo=FALSE, message=FALSE, warning = FALSE, fig.align='center'}
dezimsurvey %>% 
  select(ID, MigHin, MigHin_short, contains("self"), -lire_self) %>% 
  pivot_longer(contains("self"), names_to = "issue", values_to = "position") %>% 
  mutate(issue = stri_replace_all_regex(issue, 
                                        c("econ_self", "immi_self", "soci_self"),
                                        c("redistribution", "immigration", "societal"), vectorise_all = FALSE) %>% 
           factor(., levels = c("redistribution", "immigration", "societal"))) %>% 
  ggplot(aes(x = position, y = MigHin_short, color = issue)) +
  stat_summary(fun.data = mean_se, geom = "pointrange",
               position = position_dodge(.3), size = .3, witdh = .2) +
  scale_x_continuous(limits = c(0, 10),
                     breaks = seq(0, 10, 1),
                     minor_breaks = NULL) +
  guides(color = guide_legend(title = "issue: ")) +
  labs(y = "migration background", 
       x = "position on issue") +
  theme_bw() +
  theme(
    legend.position = "bottom"
  )

ggsave("graphs/fig2_positions_by_migrantbackground.jpeg", dpi = 300, device = "jpeg")
```

# Regression Models

## additive models for all issues

First, we run the regression models.

```{r, echo=FALSE, message=FALSE, warning = FALSE, fig.align='center'}
# regex for nice variable names for regression tables / coefficient plots
regex_vec <- c(
  # depvars
  "econ_self" = "redistribution",
  "immi_self" = "immigration",
  "soci_self" = "societal",
  # indepvars
  "MigHin_shortother" = "migration backround:\nother",
  "MigHin_shortItalian" = "migration backround:\nItalian",
  "MigHin_shortTurkish" = "migration backround:\nTurkish",
  "MigHin_shortRussian" = "migration backround:\nRussian",
  "birthcntry_not_deu" = "first generation\nmigrant",
  "relig_memreligious" = "religious",
  "ctzship_gertrifft zu" = "German citizenship",
  "educationdiploma" = "high school/\nuniversity diploma",
  "east" = "East Germany",
  "gndr_female" = "female",
  "as.numeric\\(age\\)" = "age",
  "migration backround:\nTurkish:first generation\nmigrant" = "mb Turkish X first gen.",
  "migration backround:\nother:first generation\nmigrant" = "mb other X first gen.",
  "migration backround:\nItalian:first generation\nmigrant" = "mb Italian X first gen.",
  "migration backround:\nRussian:first generation\nmigrant" = "mb Russian X first gen.")
  


issues <- c("econ_self", "immi_self", "soci_self")


# add independent variables
regformulas1 <- str_c(issues, " ~ MigHin_short + birthcntry_not_deu + relig_mem + ctzship_ger + education + east + gndr_female + as.numeric(age)")

regmodels1 <- regformulas1 %>% map(., ~as.formula(.)) %>% 
  map(., ~lm(., data = as.data.frame(dezimsurvey)#, weights = weight_gesamt   #Nutzen wir jetzt weights oder nicht?
             )) %>% 
  set_names(issues)
```

## coefficient plot base models

This code replicates figure 3.

```{r, echo=FALSE, message=FALSE, warning = FALSE, fig.align='center'}
# Koeffizientenplots
reg_tab <- regmodels1 %>% 
  map(., ~tidy(.x)) %>% 
  bind_rows(.id = "depvar") %>% 
  left_join(
    regmodels1 %>% 
      map(., ~confint(.x, level = 0.95)) %>% 
      map(., ~as_tibble(.x, rownames = "term") %>% select(term, conf_low = 2, conf_high = 3)) %>% 
      bind_rows(.id = "depvar")
  ) %>% 
  # make nicer names
  mutate(across(c(term, depvar), ~stri_replace_all_regex(.x, names(regex_vec), unname(regex_vec), vectorise_all = FALSE)))
  

reg_tab %>% 
  # drop variables from coefplot
  filter(term != "(Intercept)") %>% 
  mutate(significant = case_when(
    p.value < 0.05 ~ "significant",
    TRUE ~ "insignificant"
  )) %>% 
  ggplot(aes(x = term, y = estimate)) +
  geom_hline(yintercept = 0, 
             colour = gray(1/2), lty = 2) +
  geom_point(aes(x = term, 
                 y = estimate, color = significant)) + 
  geom_linerange(aes(x = term, 
                     ymin = conf_low,
                     ymax = conf_high,
                     color = significant),
                 lwd = 1/2) +
  
  scale_color_manual(values = c("grey", "black")) +
 # scale_x_discrete(labels = party_names) +
  guides(color = "none") +
  facet_wrap(~depvar) +
  labs(y = "estimate", x = "") +
  coord_flip() + 
  theme_bw() 

ggsave("graphs/fig3_coefplot_pos_by_migbckg.jpeg", dpi = 300, device = "jpeg")
```


## Coefficient Plot hypothesis 1 - MigHin:First generation

This code replicates figure 4.

```{r, echo=FALSE, message=FALSE, warning = FALSE, fig.align='center'}

# new reg-formular
regformulas2 <- str_c(issues, " ~ MigHin_short + birthcntry_not_deu + relig_mem + ctzship_ger + education + east + gndr_female + as.numeric(age) + MigHin_short*birthcntry_not_deu")

regmodels2 <- regformulas2 %>% map(., ~as.formula(.)) %>% 
  map(., ~lm(., data = as.data.frame(dezimsurvey)#, weights = weight_gesamt   #Nutzen wir jetzt weights oder nicht?
             )) %>% 
  set_names(issues)

# coefficient plots
reg_tab <- regmodels2 %>% 
  map(., ~tidy(.x)) %>% 
  bind_rows(.id = "depvar") %>% 
  left_join(
    regmodels2 %>% 
      map(., ~confint(.x, level = 0.95)) %>% 
      map(., ~as_tibble(.x, rownames = "term") %>% select(term, conf_low = 2, conf_high = 3)) %>% 
      bind_rows(.id = "depvar")
  ) %>% 
  # make nicer names
  mutate(across(c(term, depvar), ~stri_replace_all_regex(.x, names(regex_vec), unname(regex_vec), vectorise_all = FALSE)))
  

reg_tab %>% 
  # drop variables from coefplot
  filter(term != "(Intercept)") %>%  
  mutate(significant = case_when(
    p.value < 0.05 ~ "significant",
    TRUE ~ "insignificant"
  )) %>% 
  ggplot(aes(x = term, y = estimate)) +
  geom_hline(yintercept = 0, 
             colour = gray(1/2), lty = 2) +
  geom_point(aes(x = term, 
                 y = estimate,
                 color = significant)) + 
  geom_linerange(aes(x = term, 
                     ymin = conf_low,
                     ymax = conf_high,
                     color = significant),
                 lwd = 1/2) +
  scale_color_manual(values = c("grey", "black")) +
  guides(color = "none") +
  facet_wrap(~depvar) +
  labs(y = "estimate", x = "") +
  coord_flip() + 
  theme_bw() 

ggsave("graphs/fig4_coefplot_H1_MBxFirstGen.jpeg", dpi = 300, device = "jpeg")
```



## Religion and Religiosity

This code replicates figure 5.

```{r, echo=FALSE, message=FALSE, warning = FALSE, fig.align='center'}

# run model
model <- lm(
  soci_self ~ MigHin_short + birthcntry_not_deu + relig_mem + ctzship_ger + education + east + gndr_female + as.numeric(age) + MigHin_short*relig_mem,
  data = dezimsurvey
)


pred_values <- predictions(model,
                          newdata = datagrid(
                            MigHin_short = c("Turkish", "Russian", "Italian", "none", "other"),
                            relig_mem = c("religious", "non religious")))

pred_values %>% 
  ggplot(aes(x = MigHin_short, 
             y = estimate,
             ymin = conf.low,
             ymax = conf.high,
             color = relig_mem,
             fill = relig_mem
             )) +
  geom_linerange(position = position_dodge(width = .5), show.legend = FALSE) +
  geom_point(position = position_dodge(width = .5)) +
  scale_y_continuous(limits = c(0, 10),
                     labels = seq(0, 10, 1),
                     breaks = seq(0, 10, 1)) +
  coord_flip() +
  labs(
    title = "",
    y = "progressive vs. traditional",
    x = "migration background"
  ) +
  guides(fill = "none",
         color = guide_legend("")) +
  scale_color_hue(labels = c("secular", "religious")) +
  theme_bw() +
  theme(
    plot.title = element_text(size = 11, hjust = .5, face = "italic"),
    axis.title.x = element_text(size = 11, hjust = .5, face = "italic")
  )


ggsave("graphs/fig5_predictions_interaction_migbackXrelig_mem.jpeg", dpi = 300, device = "jpeg")
```

## Strength of Religiosity on soci_self by Migration Background

This code replicates figure 6.

```{r, echo=FALSE, message=FALSE, warning = FALSE, fig.align='center'}
model <- lm(
  soci_self ~ MigHin_short*relig_strength + birthcntry_not_deu,
  data = dezimsurvey
  )

pred_values <- predictions(model,
                          newdata = datagrid(
                            MigHin_short = c("Turkish", "Russian", "Italian", "none", "other"),
                            relig_strength = c(1:6)))
  
pred_values %>%
  mutate(MigHin_short = factor(MigHin_short, levels = c(
     "Russian", "Turkish", "Italian", "other", "none"))) %>% 
  ggplot(aes(x = relig_strength,
             y = estimate,
             ymin = conf.low,
             ymax = conf.high)) +
     geom_linerange(position = position_dodge(width = .5), show.legend = FALSE) +
  geom_point(position = position_dodge(width = .5)) +
    scale_y_continuous(limits = c(0, 10),
                     breaks = seq(0, 10, 1),
                     minor_breaks = NULL) +
    scale_x_continuous(limits = c(1, 6),
                        breaks = seq(1, 6),
                        minor_breaks = NULL
                        ) +
    facet_wrap(~MigHin_short) +
    coord_flip() +
    labs(x = "Strength of Religiosity",
       y = "progressive vs. traditional") +
    theme_bw() +
    theme(
    legend.position = "bottom"
    )

ggsave("graphs/fig6_predictions_strength_religiosity.jpeg", dpi = 300, device = "jpeg")
```

# APPENDIX

## Societal Policies

We run the models again, for tables A2, A3, and A4.
```{r, echo=FALSE, message=FALSE, warning = FALSE, fig.align='center', comment=NA}
soc1 <- lm(soci_self ~ MigHin_short + birthcntry_not_deu + relig_mem + ctzship_ger + education + east + gndr_female + as.numeric(age) 
         , data = dezimsurvey
  )


soc2 <- lm(soci_self ~ MigHin_short + birthcntry_not_deu + relig_mem + MigHin_short*relig_mem  + ctzship_ger + education + east + gndr_female + as.numeric(age)
         , data = dezimsurvey
  )
```

```{r, echo=FALSE, message=FALSE, warning = FALSE, fig.align='center', comment=NA, results='asis'}
stargazer(soc1, soc2
          , covariate.labels = c("Mig. Backgr. (other)", "Mig. Backgr. (Italy)", "Mig. Backgr. (Turkey)", "Mig. Backgr. (Russia)", "First Gen.", "Religious", " German citizenship", "High school/university diploma", "East Germany", "Female", "Age", "MB: other X Religious", "MB: Italy X Religious","MB: Turkey X Religious", "MB: Russia X Religious")
          , title = "Societal Issues Self Placement"
          , dep.var.labels = "Selfplacement on Societal Issues"
          , model.names = T
         , type = "html",
     #   , type = "text",
       font.size =  "tiny",
       column.sep.width = "3pt",
       no.space = TRUE,
       header = FALSE
          )
``` 



## Immigration Policies
```{r, echo=FALSE, message=FALSE, warning = FALSE, fig.align='center', comment=NA, results='asis'}
immi1 <- lm(immi_self ~ MigHin_short + birthcntry_not_deu + relig_mem + ctzship_ger + education + east + gndr_female + as.numeric(age) 
         , data = dezimsurvey
  )


immi2 <- lm(immi_self ~ MigHin_short + birthcntry_not_deu + relig_mem + MigHin_short*relig_mem  + ctzship_ger + education + east + gndr_female + as.numeric(age)
         , data = dezimsurvey
  )
```

```{r, echo=FALSE, message=FALSE, warning = FALSE, fig.align='center', comment=NA, results='asis'}
stargazer(immi1, immi2
          , covariate.labels = c("Mig. Backgr. (other)", "Mig. Backgr. (Italy)", "Mig. Backgr. (Turkey)", "Mig. Backgr. (Russia)", "First Gen.", "Religious", " German citizenship", "High school/university diploma", "East Germany", "Female", "Age", "MB: other X Religious", "MB: Italy X Religious","MB: Turkey X Religious", "MB: Russia X Religious")
          , title = "Immigration Issues Self Placement"
          , dep.var.labels = "Selfplacement on Immigration Issues"
          , model.names = T
         , type = "html",
     #   , type = "text",
       font.size =  "tiny",
       column.sep.width = "3pt",
       no.space = TRUE,
       header = FALSE
          )
``` 

## Economic Policies
```{r, echo=FALSE, message=FALSE, warning = FALSE, fig.align='center', comment=NA}
econ1 <- lm(econ_self ~ MigHin_short + birthcntry_not_deu + relig_mem + ctzship_ger + education + east + gndr_female + as.numeric(age) 
         , data = dezimsurvey
  )


econ2 <- lm(econ_self ~ MigHin_short + birthcntry_not_deu + relig_mem + MigHin_short*relig_mem  + ctzship_ger + education + east + gndr_female + as.numeric(age)
         , data = dezimsurvey
  )
```

```{r, echo=FALSE, message=FALSE, warning = FALSE, fig.align='center', comment=NA,  results='asis'}
stargazer(econ1, econ2
          , covariate.labels = c("Mig. Backgr. (other)", "Mig. Backgr. (Italy)", "Mig. Backgr. (Turkey)", "Mig. Backgr. (Russia)", "First Gen.", "Religious", " German citizenship", "High school/university diploma", "East Germany", "Female", "Age", "MB: other X Religious", "MB: Italy X Religious","MB: Turkey X Religious", "MB: Russia X Religious")
          , title = "Economic Issues Self Placement"
          , dep.var.labels = "Selfplacement on Economic Issues"
          , model.names = T
         , type = "html",
     #   , type = "text",
       font.size =  "tiny",
       column.sep.width = "3pt",
       no.space = TRUE,
       header = FALSE
          )
``` 


## Strength of Religiosity

As a robustness check, we exchange religiosity (yes/no) with an indicator of how strongly religious an individual is. 

```{r, echo=FALSE, message=FALSE, warning = FALSE, fig.align='center', comment=NA, results='asis'}
# Societal
anh1 <- lm(soci_self ~ MigHin_short + birthcntry_not_deu + relig_strength + ctzship_ger + education + east + gndr_female + as.numeric(age)
         , data = dezimsurvey
  )

anh2 <- lm(soci_self ~ MigHin_short + birthcntry_not_deu + relig_strength + ctzship_ger + MigHin_short*relig_strength + education + east + gndr_female + as.numeric(age) + ctzship_ger
         , data = dezimsurvey
  )

# Immigration
anh3 <- lm(immi_self ~ MigHin_short + birthcntry_not_deu + relig_strength + ctzship_ger + education + east + gndr_female + as.numeric(age)
         , data = dezimsurvey
  )

anh4 <- lm(immi_self ~ MigHin_short + birthcntry_not_deu + relig_strength + ctzship_ger + MigHin_short*relig_strength + education + east + gndr_female + as.numeric(age) + ctzship_ger
         , data = dezimsurvey
  )

# Economic
anh5 <- lm(econ_self ~ MigHin_short + birthcntry_not_deu + relig_strength + ctzship_ger + education + east + gndr_female + as.numeric(age)
         , data = dezimsurvey
  )

anh6 <- lm(econ_self ~ MigHin_short + birthcntry_not_deu + relig_strength + ctzship_ger + MigHin_short*relig_strength + education + east + gndr_female + as.numeric(age) + ctzship_ger
         , data = dezimsurvey
  )
``` 

The following chunk replicates table A5. 

```{r, echo=FALSE, message=FALSE, warning = FALSE, fig.align='center', comment=NA,  results='asis'}
stargazer(anh1, anh2, anh3, anh4, anh5, anh6
          , covariate.labels = c("Mig. Backgr. (other)", "Mig. Backgr. (Italy)", "Mig. Backgr. (Turkey)", "Mig. Backgr. (Russia)", "First Gen.", "Strength of Religiosity", " German citizenship", "High school/university diploma", "East Germany", "Female", "Age", "MB: other X Strength of Religiosity", "MB: Italy X Strength of Religiosity","MB: Turkey X Strength of Religiosity", "MB: Russia X Strength of Religiosity")
          , title = "Strength of Religiosity Effects"
      #    , dep.var.labels = "Selfplacement on Economic Issues (welfare vs liberal)"
          , model.names = T
         , type = "html",
       # , type = "text",
       font.size =  "tiny",
       column.sep.width = "3pt",
       no.space = TRUE,
       header = FALSE
          )
``` 


## Party Positions by Respondees

The following chunk replicates figure A1.

```{r, echo=FALSE, message=FALSE, warning = FALSE, fig.align='center'}
dezimsurvey %>% 
  select(ID, MigHin, MigHin_short, matches("econ_|soci_|immi_")) %>% 
  pivot_longer(matches("econ_|soci_|immi_"), 
               names_to = "issue", values_to ="position") %>% 
  separate(issue, into = c("issue", "party")) %>% 
  filter(party != "self") %>% 
  mutate(issue = stri_replace_all_regex(issue, 
                                        c("econ", "immi", "soci"),
                                        c("redistribution", "immigration", "societal"), vectorise_all = FALSE) %>% 
           factor(., levels = c("left-right", "redistribution", "immigration", "societal"))) %>% 
  ggplot(aes(x = MigHin_short, y = position, color = party)) +
  stat_summary(fun.data = mean_se, geom = "pointrange",
               position = position_dodge(.3), size = .3) +
  scale_y_continuous(limits = c(0, 10),
                     breaks = seq(0, 10, 1),
                     minor_breaks = NULL) +
  scale_color_manual(values = party_colors,
                     labels = party_names) +
  guides(color = guide_legend(title = "issue")) +
  facet_wrap(~issue) +
  coord_flip() +
  labs(x = "migration background", 
       y = "position on issue") +
  theme_bw() +
  theme(
    legend.position = "bottom"
  )

ggsave("graphs/figa1_respondents_party_position_assessment.jpeg", dpi = 300, device = "jpeg")
```

# This last:

## Summary Statistics

This replicates Table A1 in the paper. Needs to be run last, because of the as.numeric command. Note that if you want to rerun models from above after running the following chunks, you will have to reload the data.

```{r, echo=FALSE, message=FALSE, warning = FALSE, fig.align='center'}

dezimsurvey$age <- as.numeric(dezimsurvey$age)
vtable::sumtable(dezimsurvey, vars = c("soci_self", "econ_self", "immi_self", "birthcntry_not_deu", "relig_mem", "ctzship_ger", "education", "east", "gndr_female", "age")
         , title = "Summary Statistics"
         , out = "latex"
         )
```